package com.legleg.db;

import com.legleg.data.Album;
import org.apache.commons.lang.StringUtils;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-1-4
 * Time: 上午10:07
 * To change this template use File | Settings | File Templates.
 */
public class AlbumDao extends Dao {
    public static boolean ifCrawled(Album album){
        if(album==null || album.getPageurl()==null) return true;
        String sql = "select count(*) c from album where pageurl='"+ StringUtils.trimToEmpty(album.getPageurl())+"'";
        return  (Long)findBy(sql, "c", null)==0?false:true;
    }

    public static long insert(Album album){
        long ret = insert("insert into album(title,description,pageurl,category,tags,picnum,success,crawledfeed,crawledsite) values(?,?,?,?,?,?,?,?,?)",
                album.getTitle(),
                album.getDescription(),
                album.getPageurl(),
                album.getCategory(),
                album.getTags(),
                album.getPicnum(),
                album.getSuccess(),
                album.getCrawledfeed(),
                album.getCrawledsite()
                );
        if(ret>-1) album.setId(ret);
        return ret;
    }

    public static int update(Album album){
        return update(
                "update album set title=?,description=?,pageurl=?,category=?,tags=?,picnum=?,success=?,crawledfeed=?,crawledsite=? where id=?",
                album.getTitle(),
                album.getDescription(),
                album.getPageurl(),
                album.getCategory(),
                album.getTags(),
                album.getPicnum(),
                album.getSuccess(),
                album.getCrawledfeed(),
                album.getCrawledsite(),
                album.getId()
        );
    }

    public static List<Album> queryRefresh(int start,int pagesize){
        String sql = "select a.* from album a,refresh r where a.id=r.id order by r.createdtime desc limit "+start+","+pagesize;
        List<Album> ret = list(sql,Album.class);
        return ret;
    }

    public static List<Album> queryHot(int start,int pagesize){
        String sql = "select a.* from album a,hot h where a.id=h.id order by h.createdtime desc limit "+start+","+pagesize;
        List<Album> ret = list(sql,Album.class);
        return ret;
    }

    public static List<Album> queryByTag(String tag, int start,int pagesize){
        String sql = "select * from album where tags like '%"+tag+"%' order by id limit "+start+","+pagesize;
        List<Album> ret = list(sql,Album.class);
        return ret;
    }

    public static Album findById(long id){
        return (Album) find("select * from album where id=?",Album.class,id);
    }
    
    public static List<String> queryAllTags(){
        List<String> ret = list("select tags from album",String.class);
        return ret;
    }

}
